//连接数据库
'use strict';
var mysql = require('mysql');
// 数据库配置
module.exports = class SQL {
    constructor() {
        this.pool = mysql.createPool(this.config)
    }
    config = {
        host: 'localhost',
        port: 3306,
        user: 'root',
        password: '123456',
        database: 'piano',
        table: 'wzm'
    }
    execPromise(config) {
        // 异步执行
        return new Promise((resolve, reject) => {
            this.pool.getConnection(function (err, connection) {
                if (err) {
                    reject(err)
                } else {
                    connection.query(config.sql, config.params, (err, rows) => {
                        if (err) {
                            reject(err)
                        } else {
                            resolve(rows)
                        }
                        connection.release()
                    })
                }
            })
        })
    }
    exec(config) {
        // 异步执行
        this.pool.getConnection(function (err, connection) {
            if (err) {
                console.log('connection error:', err)
            } else {
                connection.query(config.sql, config.params, (err, rows, fields) => {
                    if (err) {
                        console.log('query error:', err)
                    } else if (config.callback) {
                        config.callback(rows)
                    }
                    connection.release()
                })
            }
        })
    }
    // =================== 专有方法 ===================
    markSelected(ids) {
        const sql = 'UPDATE wzm SET isSelected = 1 where id = ?';
        this.pool.getConnection((err, connection) => {
            if (err) {
                console.log('connection error:', err)
            } else {
                ids.forEach(id => {
                    connection.query(sql, [id], (err, rows, fields) => {
                        if (err) console.log('query error:', err)
                    })
                });
                connection.release()
            }
        })
    }
    clearAllSelected() {
        const sql = 'UPDATE wzm SET isSelected = 0';
        this.pool.getConnection((err, connection) => {
            if (err) {
                console.log('connection error:', err)
            } else {
                connection.query(sql, (err, rows, fields) => {
                    if (err) console.log('query error:', err)
                })
                connection.release()
                this.pool.end();
            }
        })
    }
};


